package cn.ztuo.bitrade.job;


import cn.ztuo.bitrade.constant.TransactionType;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.FiworkWalletUtil;
import cn.ztuo.bitrade.util.HttpUtil;
import cn.ztuo.bitrade.util.RedisUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class EthUsdtAutoArriveOptimize {

    @Autowired
    private CoinService coinService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private MemberDepositService memberDepositService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MemberTransactionService memberTransactionService;

    private static String COINNAMETWO = "USDT";

    private static String BLOCKNUM = "5";

    private static Integer END_BLOCKNUM = 100;



    /**
     * 定义开始区块，请求代币的交易信息
     *
     * @param address 提币地址
     * @return
     */
    private JSONObject sendETHTokenRequest(String address, String startblock) {
        int startBlockInt = Integer.parseInt(startblock);
        int endBlock = startBlockInt + END_BLOCKNUM;
        log.info("------- 结束区块 = " + endBlock);
        String url = "http://api-cn.etherscan.com/api?module=account&action=txlist&address=" + address + "&startblock=" + startblock + "&endblock=" + endBlock + "&sort=asc&apikey=TEP6G8KH3NT4RKMENMCQ4ZEKG2TAZKD852";
        String result = HttpUtil.URLGet(url, null);
        return JSONObject.parseObject(result);
    }

    /**
     * 获取ETH最高区块
     *
     * @param key 获取存储Redis的区块key
     * @return
     * @throws IOException
     */
    private String getBlockNumber(String key) throws IOException {
        if (!redisUtil.hasKey(key)) {
            redisUtil.set(key, String.valueOf(FiworkWalletUtil.getBlockNumber()));
        }
        return String.valueOf(redisUtil.get(key));
    }

    private void setBlockNumber(String key) throws IOException {
        redisUtil.set(key, String.valueOf(FiworkWalletUtil.getBlockNumber()));
    }
    private void setBlockNumberForEndBlock(String key,String value) throws IOException {
        redisUtil.set(key, value);
    }

    /**
     * ETH代币USDT到账方法
     */
    @Scheduled(fixedDelay = 2* 60 * 1000)
    @Transactional
    public void ethTokenRecordedJob() {
//        BigDecimal startBlock = BigDecimal.ZERO;
//        try {
////            startBlock = new BigDecimal(getBlockNumber(COINNAMETWO + "_BLOCK_NUMBER"));
//            startBlock = BigDecimalUtils.sub(new BigDecimal(getBlockNumber(COINNAMETWO + "_BLOCK_NUMBER")), new BigDecimal(BLOCKNUM));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        log.info("USDT查询到账任务开始，当前时间 =  " + LocalDateTime.now() + "------- 开始区块 = " + startBlock);
//        JSONObject jsonObject = null;
//        Coin coin = coinService.findByUnit(COINNAMETWO);
//        // 获取到所有ETH地址
//        List<MemberWallet> memberInfos = memberWalletService.selectCoininfo(coin.getUnit());
//        try {
//            // 拿合约地址查询所有交易
//            jsonObject = sendETHTokenRequest("0xdac17f958d2ee523a2206206994597c13d831ec7", startBlock.toPlainString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        JSONObject finalJsonObject = jsonObject;
//        String withdrawScale = coin.getWithdrawScale();
//        memberInfos.forEach(wallet -> {
//            if ("OK".equals(finalJsonObject.getString("message")) && 1 == finalJsonObject.getInteger("status") && finalJsonObject.get("result") != null) {
//                // result转为List
//                JSONArray jsonArray = finalJsonObject.getJSONArray("result");
//                List<JSONObject> resultList = jsonArray.toJavaList(JSONObject.class);
//                if (resultList != null && resultList.size() > 0) {
//                    resultList.forEach(result -> {
//                        // 获取到入账地址 比对 命中时去数据库中查询该txid是否已经记录 如已经记录则跳过，否则入账该记录
//                        String input = result.getString("input");
//                        if (input.length() == 138 && result.getInteger("txreceipt_status") == 1) {
//                            String toAddress = "0x" + input.substring(34, 74);
////                        String toAddress = result.getString("to");
//                            String fromAddress = result.getString("from");
//                            if (wallet.getAddress().equals(toAddress)) {
//                                String txid = result.getString("hash");
//                                if (!memberDepositService.findTxid(toAddress, txid)) {
//                                    // 截取出16进制数量 转为10进制除以精度得到数量
//                                    String amountHexadecimal = input.substring(74);
//                                    Long amountLong = Long.parseLong(amountHexadecimal, 16);
//                                    BigDecimal amount = BigDecimalUtils.div(new BigDecimal(amountLong), new BigDecimal(withdrawScale));
//                                    MemberDeposit depositRecord = new MemberDeposit();
//                                    depositRecord.setAddress(toAddress);
//                                    depositRecord.setAmount(amount);
//                                    depositRecord.setTxid(txid);
//                                    depositRecord.setMemberId(wallet.getMemberId());
//                                    depositRecord.setUnit(COINNAMETWO);
//                                    depositRecord.setCreateTime(new Date());
//                                    Member member = memberService.findOne(wallet.getMemberId());
//                                    depositRecord.setUsername(member.getUsername());
//                                    memberDepositService.save(depositRecord);
//                                    memberWalletService.increaseBalance(wallet.getId(), amount);
//                                    //充值到账记录
//                                    MemberTransaction transaction = new MemberTransaction();
//                                    transaction.setAmount(amount);
//                                    transaction.setSymbol("USDT");
//                                    transaction.setAddress(fromAddress);
//                                    transaction.setMemberId(wallet.getMemberId());
//                                    transaction.setType(TransactionType.RECHARGE);
//                                    transaction.setFee(BigDecimal.ZERO);
//                                    transaction.setCreateTime(new Date());
//                                    transaction.setRemark("充值");
//                                    memberTransactionService.save(transaction);
//                                }
//                            }
//                        }
//                    });
//                }
//            }
//        });
//        // 获取最新区块存入REDIS
//        try {
//            BigDecimal endblock = BigDecimalUtils.add(startBlock, new BigDecimal(END_BLOCKNUM));
//            BigDecimal newBlockNumber = new BigDecimal(FiworkWalletUtil.getBlockNumber());
//            if(endblock.compareTo(newBlockNumber)>=0){
//                log.info("大于最新区块，startBlock特殊处理");
//                endblock = newBlockNumber.subtract(new BigDecimal(END_BLOCKNUM));
//            }
//            setBlockNumberForEndBlock(COINNAMETWO + "_BLOCK_NUMBER",endblock.toPlainString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        log.info("USDT查询到账任务结束，当前时间为：" + LocalDateTime.now());
    }

}
